package com.eightbears.beboy;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.redpacket.utils.RedPacketUtil;
import com.easemob.redpacketsdk.constant.RPConstant;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.cache.DistrictCache;
import com.eightbears.beboy.base.cache.FriendsCache;
import com.eightbears.beboy.base.cache.GroupCache;
import com.eightbears.beboy.base.cache.GroupMemberCache;
import com.eightbears.beboy.base.cache.MessageStatusCache;
import com.eightbears.beboy.base.cache.MyAddressCache;
import com.eightbears.beboy.base.util.CommonAPI;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.DensityUtil;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.BlurringView;
import com.eightbears.beboy.base.view.XCSlideView;
import com.eightbears.beboy.base.view.dialog.DefaultDialog;
import com.eightbears.beboy.base.view.popupwindow.MultipeSelectionPopup;
import com.eightbears.beboy.entity.ChatGroupEntity;
import com.eightbears.beboy.entity.FriendEntity;
import com.eightbears.beboy.entity.LocationEntity;
import com.eightbears.beboy.entity.StaticDataEntity;
import com.eightbears.beboy.entity.UserEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.chat.DemoHelper;
import com.eightbears.beboy.ui.chat.base.PreferenceManager;
import com.eightbears.beboy.ui.chat.base.db.DemoDBManager;
import com.eightbears.beboy.ui.chat.base.db.InviteMessgeDao;
import com.eightbears.beboy.ui.chat.base.runtimepermissions.PermissionsManager;
import com.eightbears.beboy.ui.chat.base.runtimepermissions.PermissionsResultAction;
import com.eightbears.beboy.ui.chat.ui.activity.ChatActivity;
import com.eightbears.beboy.ui.login.LoginActivity;
import com.eightbears.beboy.ui.merchant.activity.ShopApplyActivity;
import com.eightbears.beboy.ui.merchant.activity.ShopManageActivity;
import com.eightbears.beboy.ui.user.activity.ByVipActivity;
import com.eightbears.beboy.ui.user.activity.FocusShopActivity;
import com.eightbears.beboy.ui.user.activity.MyClientActivity;
import com.eightbears.beboy.ui.user.activity.MyPostActivity;
import com.eightbears.beboy.ui.user.activity.OrderListActivity;
import com.eightbears.beboy.ui.user.activity.RedActivity;
import com.eightbears.beboy.ui.user.activity.SetMealOrderActivity;
import com.eightbears.beboy.ui.user.activity.SettingActivity;
import com.eightbears.beboy.ui.user.activity.UserPublishInfo;
import com.eightbears.beboy.ui.user.fragment.FindFragment;
import com.eightbears.beboy.ui.user.fragment.HomeFragment;
import com.eightbears.beboy.ui.user.fragment.MessageFragment;
import com.eightbears.beboy.ui.user.fragment.MyFragment;
import com.eightbears.beboy.ui.user.fragment.ShopFragment;
import com.eightbears.greendao.District;
import com.eightbears.greendao.Friends;
import com.eightbears.greendao.GroupList;
import com.eightbears.greendao.GroupMember;
import com.eightbears.greendao.MessageStatus;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMContactListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.exceptions.HyphenateException;
import com.makeramen.roundedimageview.RoundedImageView;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.cache.DistrictCache.CODE_CITY;
import static com.eightbears.beboy.base.cache.DistrictCache.CODE_DISTRICT;
import static com.eightbears.beboy.base.cache.DistrictCache.CODE_PROVINCE;
import static com.eightbears.beboy.base.util.CommonAPI.ACCOUNT_REMOVED;
import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_USER_ID;
import static com.eightbears.beboy.base.util.CommonAPI.URL_FRIENDS_LIST;
import static com.eightbears.beboy.base.util.CommonAPI.URL_GROUP_LIST;
import static com.eightbears.beboy.base.util.CommonAPI.URL_RESET_USERDATA;
import static com.eightbears.beboy.base.util.CommonAPI.URL_USER_DATA;
import static com.eightbears.beboy.ui.merchant.activity.ReservationShopActivity.EVENT_RESERVATION_SUCCESS;
import static com.eightbears.beboy.ui.user.activity.ByVipActivity.EVENT_UPDATE_USER_STATUS;
import static com.eightbears.beboy.ui.user.activity.SettingActivity.EVENT_EXIT;
import static com.eightbears.beboy.ui.user.activity.SettingActivity.EVENT_FINISH;
import static com.eightbears.beboy.ui.user.activity.SettingActivity.EVENT_USER_HEAD_UPDATE;
import static com.eightbears.beboy.ui.user.fragment.MyFragment.EVENT_UPDATE_USERINFO;

public class MainActivity extends BaseActivity {

    public static final String EVENT_VIP_CANCEL = "vipCancel";
    public static final String EVENT_REFRESH_LEFT = "refreshLeft";
    public static final String EVENT_ADD_FRIENDS = "addFrends";

    @BindView(R.id.tv_home_text)
    TextView tv_home_text;
    @BindView(R.id.tv_message_text)
    TextView tv_message_text;
    @BindView(R.id.tv_find_text)
    TextView tv_find_text;
    @BindView(R.id.tv_shop_text)
    TextView tv_shop_text;
    @BindView(R.id.unread_msg_number)
    TextView unread_msg_number;
    @BindView(R.id.view_loading)
    View view_loading;
    @BindView(R.id.tv_loading_text)
    TextView tv_loading_text;
    private RoundedImageView iv_user_head;
    private TextView tv_nickname;
    private ImageView iv_vip;
    private ImageView iv_head_bg;
    private BlurringView blurring_view;
    private RelativeLayout rl_setting;
    private RelativeLayout rl_red;
    private RelativeLayout rl_user_publish_info;
    private RelativeLayout rl_vip;
    private RelativeLayout rl_my_buy;
    private RelativeLayout rl_fouces_shop;
    private RelativeLayout rl_my_book;
    private RelativeLayout rl_shop_entry;
    private RelativeLayout rl_shop_manage;
    private RelativeLayout rl_my_set_meal;
    private RelativeLayout rl_client;
    private LinearLayout ll_exit;

    private Fragment mTempFragment;
    private HomeFragment homeFragment;
    private MessageFragment messageFragment;
    private ShopFragment shopFragment;
    private FindFragment findFragment;
    private FragmentManager mFragmentManager;

    private InviteMessgeDao inviteMessgeDao;
    private LocalBroadcastManager broadcastManager;
    private BroadcastReceiver broadcastReceiver;
    private DefaultDialog.Builder mBuilder;
    private XCSlideView mSlideViewLeft;
    private long mExitTime;
    private boolean isCurrentAccountRemoved = false; // 账户被删除
    private boolean isExceptionDialogShow = false;
    public boolean isConflict = false; // 在其他设备登录
    public int currentTabIndex = 0;

    private UserEntity mUser;
    private MyFragment mMyFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String packageName = getPackageName();
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            if (!pm.isIgnoringBatteryOptimizations(packageName)) {
                try {
                    Intent intent = new Intent();
                    intent.setAction(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                    intent.setData(Uri.parse("package:" + packageName));
                    startActivity(intent);
                } catch (Exception e) {

                }
            }
        }

        // 登录被踢出
        if (savedInstanceState != null && savedInstanceState.getBoolean(ACCOUNT_REMOVED, false)) {
            DemoHelper.getInstance().logout(false, null);
            finish();
            startActivity(new Intent(this, LoginActivity.class));
            return;
        } else if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) {
            finish();
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        initUserLocation();
        mUser = SPUtil.getUser();
        initChat();
//        initSlideView();
        tv_home_text.setSelected(true);
        homeFragment = new HomeFragment();
        findFragment = new FindFragment();
        messageFragment = new MessageFragment();
//        shopFragment = new ShopFragment();
        mMyFragment = new MyFragment();
        mTempFragment = homeFragment;
        replaceFragment(R.id.frame_container, homeFragment);
    }

    private void initUserLocation() {
        LocationEntity locationEntity = SPUtil.getUserLocation();
        if (null != locationEntity) {
            getLocationId(locationEntity);
        }
    }

    @Override
    protected void initData() {
//        initLeftMen();
        getFriendsList();//获取联系人列表
    }

    @Override
    protected void initEvent() {
        //版本更新
        checkVersion2Update();
    }

    public void showLeftMenu() {
        mSlideViewLeft.show();
        getUserinfo();

    }

    /**
     * 获取用户数据
     */
    public void getUserinfo() {
        OkHttpUtils.get().url(URL_RESET_USERDATA + mUser.getData().getUser_id())
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("need_manager", "1")
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                try {
                    UserEntity userEntity = GsonUtil.fromJson(response, UserEntity.class);
                    if (CONNECTION_STATUS_SUCCESS.equals(userEntity.getStatus_code())) {
                        userEntity.getData().setAccess_token(SPUtil.getAccessToken());
                        SPUtil.putUser(userEntity);
                        mUser = SPUtil.getUser();
                        initLeftMenuStatus();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
            }
        });
    }

    private void registerBroadcastReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(CommonAPI.ACTION_CONTACT_CHANAGED);
        intentFilter.addAction(CommonAPI.ACTION_GROUP_CHANAGED);
        intentFilter.addAction(RPConstant.REFRESH_GROUP_RED_PACKET_ACTION);
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                updateUnreadLabel();
                //updateUnreadAddressLable();
                if (currentTabIndex == 2) {
                    if (messageFragment != null) {
                        messageFragment.refresh();
                    }
                }
                String action = intent.getAction();
//                if(action.equals(CommonAPI.ACTION_GROUP_CHANAGED)){
//                    if (EaseCommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
//                        GroupsActivity.instance.onResume();
//                    }
//                }
//                //red packet code : 处理红包回执透传消息
                if (action.equals(RPConstant.REFRESH_GROUP_RED_PACKET_ACTION)) {
                    if (messageFragment != null) {
                        messageFragment.refresh();
                    }
                }
                //end of red packet code
            }
        };
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    @TargetApi(23)
    private void requestPermissions() {
        PermissionsManager.getInstance().requestAllManifestPermissionsIfNecessary(this, new PermissionsResultAction() {
            @Override
            public void onGranted() {
            }

            @Override
            public void onDenied(String permission) {
            }
        });
    }

    /**
     * 获取所有群
     */
    private void getGroupList() {
        OkHttpUtils.get().url(URL_GROUP_LIST)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                if (response.contains(",\"data\":[]")) {
                    startLocalActivity((Activity) mContext, MainActivity.class);//已经注册登录主页面
                    return;
                }
                ChatGroupEntity groupEntity = GsonUtil.fromJson(response, ChatGroupEntity.class);
                if (response.contains(CONNECTION_STATUS_SUCCESS) && null != groupEntity) {
                    if (null != groupEntity.getData().getList()) {
                        List<GroupList> groupLists = groupEntity.getData().getList();
                        List<GroupMember> groupMembers = new ArrayList<>();
                        if (null != groupLists) {
                            GroupCache.getInstance(MainActivity.this).insertAll(groupEntity.getData().getList());
                            for (int i = 0; i < groupLists.size(); i++) {
                                GroupMember groupMember = new GroupMember();
                                groupMember.setGroupid(groupLists.get(i).getGroupid());
                                groupMember.setUserid(mUser.getData().getUser_id() + "");
                                groupMembers.add(groupMember);
                            }
                            GroupCache.getInstance(MainActivity.this).insertAll(groupLists);
                            GroupMemberCache.getInstance(MainActivity.this).insertAll(groupMembers);
                        }
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(MainActivity.this, status_error);
            }
        });
    }

    /**
     * 获取好友列表
     */
    private void getFriendsList() {
        OkHttpUtils.get().url(URL_FRIENDS_LIST)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                FriendEntity status_friend = GsonUtil.fromJson(response, FriendEntity.class);
                if (status_friend.getStatus_code().equals(String.valueOf(CONNECTION_STATUS_SUCCESS))) {
                    List<Friends> userEntities = status_friend.getData();
                    FriendsCache.getInstance(MainActivity.this).insertAll(userEntities);
                    loginChatServer();
                }
                postLocation();
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(MainActivity.this, status_error);
            }
        });
    }


    /**
     * 首页按钮
     */
    @OnClick(R.id.ll_home)
    void homeMenu() {
        initSelect();
        currentTabIndex = 0;
        tv_home_text.setSelected(true);
        switchFragment(homeFragment);
    }

    /**
     * 发现按钮
     */
    @OnClick(R.id.ll_find)
    void findMenu() {
        initSelect();
        currentTabIndex = 1;
        tv_find_text.setSelected(true);
        findFragment.showBottomView();
        switchFragment(findFragment);
    }

    /**
     * 消息按钮
     */
    @OnClick(R.id.ll_message)
    void messageMenu() {
        initSelect();
        currentTabIndex = 2;
        tv_message_text.setSelected(true);
        switchFragment(messageFragment);
    }

    /**
     * 个人按钮
     */
    @OnClick(R.id.ll_my)
    void shopMenu() {
        initSelect();
        currentTabIndex = 3;
        tv_shop_text.setSelected(true);
        switchFragment(mMyFragment);
    }


    private void initSelect() {
        tv_home_text.setSelected(false);
        tv_find_text.setSelected(false);
        tv_message_text.setSelected(false);
        tv_shop_text.setSelected(false);
    }

    /**
     * 使用实务打开fragment保证fragment单利
     *
     * @param fragment
     */
    private void switchFragment(Fragment fragment) {
        if (null == mFragmentManager) {
            mFragmentManager = getSupportFragmentManager();
        }
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        if (fragment != mTempFragment) {
            if (!fragment.isAdded()) {
                transaction.hide(mTempFragment).add(R.id.frame_container, fragment).commit();
            } else {
                transaction.hide(mTempFragment).show(fragment).commit();
            }
            mTempFragment = fragment;
        }
    }

    private MyContactListener myContactListener = new MyContactListener();

    public class MyContactListener implements EMContactListener {

        @Override
        public void onContactAdded(String username) {
            KLog.e(username);
        }

        @Override
        public void onContactDeleted(final String username) {
            runOnUiThread(new Runnable() {
                public void run() {
                    if (ChatActivity.activityInstance != null && ChatActivity.activityInstance.toChatUsername != null &&
                            username.equals(ChatActivity.activityInstance.toChatUsername)) {
                        String st10 = getResources().getString(R.string.have_you_removed);
                        Toast.makeText(MainActivity.this, ChatActivity.activityInstance.getToChatUsername() + st10, Toast.LENGTH_LONG)
                                .show();
                        KLog.e();
                        ChatActivity.activityInstance.finish();
                    }
                }
            });
            //updateUnreadAddressLable();
        }

        @Override
        public void onContactInvited(String username, String reason) {
            EventBus.getDefault().post(EVENT_ADD_FRIENDS);
            if (currentTabIndex != 2) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        unread_msg_number.setVisibility(View.VISIBLE);
                        unread_msg_number.setText("");
                    }
                });
            }
        }

        @Override
        public void onFriendRequestAccepted(String username) {

        }

        @Override
        public void onFriendRequestDeclined(String username) {
            KLog.e(username);
        }
    }

    /**
     * 消息监听回调
     */
    EMMessageListener messageListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            for (EMMessage message : messages) {
                try {
                    KLog.e(message.getStringAttribute("aaaa").toString());
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
                try {
                    int typeMessage = message.getIntAttribute("type", -1);
                    KLog.e(typeMessage);
                    if (typeMessage == 2) {
                        mUser.getData().setVip_level(0);
                        SPUtil.putUser(mUser);
                        EventBus.getDefault().post(EVENT_VIP_CANCEL);
                        showVip();
                    } else if (typeMessage == 3) {
                        int authStatus = message.getIntAttribute("auth");
                        if (authStatus == 0) {
                            mUser.getData().setIs_auth("0");
                        } else {
                            mUser.getData().setIs_auth("1");
                        }
                        EventBus.getDefault().post(EVENT_VIP_CANCEL);
                        SPUtil.putUser(mUser);
                    } else if (typeMessage == 4) {
                        int agentStatus = message.getIntAttribute("agent");
                        if (agentStatus == 0) {
                            mUser.getData().setIs_agent("0");
                        } else {
                            mUser.getData().setIs_agent("1");
                        }
                        SPUtil.putUser(mUser);
                    } else if (typeMessage == 5) {
                        int messageNum = message.getIntAttribute("manager", -1);
                        KLog.e(messageNum);
                        if (messageNum == 1) {
                            UserEntity.Shop shop = new UserEntity.Shop();
                            shop.setTitle(message.getStringAttribute("shop_title"));
                            shop.setShop_id(message.getIntAttribute("shop_id") + "");
                            shop.setUser_id(mUser.getData().getUser_id());
                            List<UserEntity.Shop> shops = new ArrayList<>();
                            shops.add(shop);
                            mUser.getData().setShops(shops);
                        } else {
                            mUser.getData().setShops(null);
                        }
                        SPUtil.putUser(mUser);
                        initLeftMenuStatus();
                    }
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }

                try {
                    if (!TextUtils.isEmpty(message.getStringAttribute(CommonAPI.transferType))) {
                        KLog.e("走吗？");
                        EventBus.getDefault().post(EVENT_UPDATE_USERINFO);
                    }
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
                MessageStatus messageStatus = MessageStatusCache.getInstance(MainActivity.this).getCacheById(message.getTo());
                if (null == messageStatus) {
                    DemoHelper.getInstance().getNotifier().onNewMsg(message);
                } else {
                    DemoHelper.getInstance().getNotifier().onNewMsgNoPlay(message);
                }
            }
            refreshUIWithMessage();
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            //red packet code : 处理红包回执透传消息
            for (EMMessage message : messages) {
                EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) message.getBody();
                final String action = cmdMsgBody.action();//获取自定义action
                if (action.equals(RPConstant.REFRESH_GROUP_RED_PACKET_ACTION)) {
                    RedPacketUtil.receiveRedPacketAckMessage(message);
                }
            }
            //end of red packet code
            refreshUIWithMessage();
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
        }
    };

    /**
     * 更新消息数量
     */
    public void updateUnreadLabel() {
        int count = getUnreadMsgCountTotal();
        if (count > 0) {
            unread_msg_number.setText(String.valueOf(count));
            unread_msg_number.setVisibility(View.VISIBLE);
        } else {
            unread_msg_number.setVisibility(View.INVISIBLE);
        }
    }

    private void refreshUIWithMessage() {
        runOnUiThread(new Runnable() {
            public void run() {
                // refresh unread count
                updateUnreadLabel();
                if (currentTabIndex == 2) {
                    // refresh conversation list
                    if (messageFragment != null) {
                        messageFragment.refresh();
                    }
                }
            }
        });
    }


    /**
     * 通知数量
     */
    public int getUnreadAddressCountTotal() {
        int unreadAddressCountTotal = 0;
        unreadAddressCountTotal = inviteMessgeDao.getUnreadMessagesCount();
        return unreadAddressCountTotal;
    }

//    /**
//     * update the total unread count
//     */
//    public void updateUnreadAddressLable() {
//        runOnUiThread(new Runnable() {
//            public void run() {
//                int count = getUnreadAddressCountTotal();
//                if (count > 0) {
//                    unread_msg_number.setVisibility(View.VISIBLE);
//                } else {
//                    unread_msg_number.setVisibility(View.INVISIBLE);
//                }
//            }
//        });
//    }

    /**
     * 获取未读消息数量
     */
    public int getUnreadMsgCountTotal() {
        return EMClient.getInstance().chatManager().getUnreadMsgsCount();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            ShowToast.showShortToast(R.string.text_alert_exit_app);
            mExitTime = System.currentTimeMillis();
        } else {
            moveTaskToBack(false);
        }
    }

    private void showExceptionDialogFromIntent(Intent intent) {
        if (!isExceptionDialogShow && intent.getBooleanExtra(CommonAPI.ACCOUNT_CONFLICT, false)) {
            showExceptionDialog(CommonAPI.ACCOUNT_CONFLICT);
        } else if (!isExceptionDialogShow && intent.getBooleanExtra(CommonAPI.ACCOUNT_REMOVED, false)) {
            showExceptionDialog(CommonAPI.ACCOUNT_REMOVED);
        } else if (!isExceptionDialogShow && intent.getBooleanExtra(CommonAPI.ACCOUNT_FORBIDDEN, false)) {
            showExceptionDialog(CommonAPI.ACCOUNT_FORBIDDEN);
        }
    }

    private int getExceptionMessageId(String exceptionType) {
        if (exceptionType.equals(CommonAPI.ACCOUNT_CONFLICT)) {
            return R.string.connect_conflict;
        } else if (exceptionType.equals(CommonAPI.ACCOUNT_REMOVED)) {
            return R.string.em_user_remove;
        } else if (exceptionType.equals(CommonAPI.ACCOUNT_FORBIDDEN)) {
            return R.string.user_forbidden;
        }
        return R.string.Network_error;
    }

    private void showExceptionDialog(String exceptionType) {
        isExceptionDialogShow = true;
        DemoHelper.getInstance().logout(false, null);
        SPUtil.loginOut();
        String st = getResources().getString(R.string.Logoff_notification);

        if (!MainActivity.this.isFinishing()) {
            if (mBuilder == null) {
                mBuilder = new DefaultDialog.Builder(MainActivity.this);
                mBuilder.setTitle(st)
                        .setMessage(getExceptionMessageId(exceptionType))
                        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mBuilder = null;
                                isExceptionDialogShow = false;
                                unregisterBroadcastReceiver();
                                startLocalActivityAndClear(MainActivity.this, SplashActivity.class);
                                dialog.dismiss();
                            }
                        });

                mBuilder.create().show();
                isConflict = true;
            }
        }
    }

    private void initSlideView() {
        int mScreenWidth = DensityUtil.getScreenWidthAndHeight(mContext)[0];
        View menuViewLeft = LayoutInflater.from(mContext).inflate(R.layout.view_left_menu, null);
        mSlideViewLeft = XCSlideView.create(this, XCSlideView.Positon.LEFT);
        mSlideViewLeft.setMenuView(MainActivity.this, menuViewLeft);
        mSlideViewLeft.setMenuWidth((int) (mScreenWidth * 0.65));
        iv_user_head = (RoundedImageView) menuViewLeft.findViewById(R.id.iv_user_head);
        tv_nickname = (TextView) menuViewLeft.findViewById(R.id.tv_nickname);
        iv_vip = (ImageView) menuViewLeft.findViewById(R.id.iv_vip);
        iv_head_bg = (ImageView) menuViewLeft.findViewById(R.id.iv_head_bg);
        blurring_view = (BlurringView) menuViewLeft.findViewById(R.id.blurring_view);
        rl_setting = (RelativeLayout) menuViewLeft.findViewById(R.id.rl_setting);
        rl_red = (RelativeLayout) menuViewLeft.findViewById(R.id.rl_red);
        rl_user_publish_info = (RelativeLayout) menuViewLeft.findViewById(R.id.rl_user_publish_info);
        rl_vip = (RelativeLayout) menuViewLeft.findViewById(R.id.rl_vip);
        rl_my_buy = (RelativeLayout) menuViewLeft.findViewById(R.id.rl_my_buy);
        rl_fouces_shop = (RelativeLayout) menuViewLeft.findViewById(R.id.rl_fouces_shop);
        rl_my_book = (RelativeLayout) menuViewLeft.findViewById(R.id.rl_my_book);
        rl_client = (RelativeLayout) menuViewLeft.findViewById(R.id.rl_client);
        ll_exit = (LinearLayout) menuViewLeft.findViewById(R.id.ll_exit);
        rl_shop_entry = (RelativeLayout) menuViewLeft.findViewById(R.id.rl_shop_entry);
        rl_shop_manage = (RelativeLayout) menuViewLeft.findViewById(R.id.rl_shop_manage);
        rl_my_set_meal = (RelativeLayout) menuViewLeft.findViewById(R.id.rl_my_set_meal);


    }

    private void initChat() {
        requestPermissions();
        inviteMessgeDao = new InviteMessgeDao(this);
        registerBroadcastReceiver();
        showExceptionDialogFromIntent(getIntent());
        EMClient.getInstance().contactManager().setContactListener(myContactListener);//设置联系人监听
        if (!SPUtil.getAlreadyLogin()) {
            getGroupList();
        }
    }

    private void initLeftMen() {
        showHead();
        tv_nickname.setText(mUser.getData().getNickname());
        initLeftMenuStatus();
        blurring_view.setBlurredView(iv_head_bg);
        blurring_view.invalidate();
        initLeftEvent();
    }

    private MultipeSelectionPopup multipeSelectionPopup;

    private void initLeftEvent() {

        rl_client.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocalActivity(MainActivity.this, MyClientActivity.class);
            }
        });
        rl_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocalActivity(MainActivity.this, SettingActivity.class);
            }
        });
        rl_red.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocalActivity(MainActivity.this, RedActivity.class);
            }
        });
        rl_user_publish_info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocalActivity(MainActivity.this, UserPublishInfo.class, PARAMS_USER_ID, mUser.getData().getUser_id());
            }
        });
        rl_vip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocalActivity(MainActivity.this, ByVipActivity.class);
            }
        });
        rl_my_buy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocalActivity(MainActivity.this, MyPostActivity.class);
            }
        });
        rl_fouces_shop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocalActivity(MainActivity.this, FocusShopActivity.class);
            }
        });
        rl_my_book.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocalActivity(MainActivity.this, OrderListActivity.class);
            }
        });
        rl_shop_entry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocalActivity(MainActivity.this, ShopApplyActivity.class);
            }
        });
        rl_shop_manage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocalActivity(MainActivity.this, ShopManageActivity.class);
            }
        });
        iv_user_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocalActivity(MainActivity.this, SettingActivity.class);
            }
        });
        rl_my_set_meal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocalActivity(MainActivity.this, SetMealOrderActivity.class);
            }
        });
        ll_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (multipeSelectionPopup == null) {
                    multipeSelectionPopup = new MultipeSelectionPopup(MainActivity.this);
                    multipeSelectionPopup.setTx_title(getString(R.string.text_exit));
                    multipeSelectionPopup.setTx_1Text(getString(R.string.text_login_out));
                    multipeSelectionPopup.setTx_2Text(getString(R.string.text_close_app));
                    multipeSelectionPopup.setOnClickItemListener(new MultipeSelectionPopup.OnClicktemListener() {
                        @Override
                        public void onClickItem(View v) {
                            switch (v.getId()) {
                                case R.id.ll_1:
                                    exitApp();
                                    multipeSelectionPopup.dismiss();
                                    break;
                                case R.id.ll_2:
                                    finish();
                                    multipeSelectionPopup.dismiss();
                                    break;
                            }
                        }


                    });
                }
                multipeSelectionPopup.showPopupWindow();
            }
        });
    }


    //退出登录
    private void exitApp() {
        unregisterBroadcastReceiver();
        MyAddressCache.getInstance(mContext).clearAllData();
        DemoHelper.getInstance().logout(true, null);
        SPUtil.loginOut();
        startLocalActivityAndClear(MainActivity.this, SplashActivity.class);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        showExceptionDialogFromIntent(intent);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean("isConflict", isConflict);
        outState.putBoolean(CommonAPI.ACCOUNT_REMOVED, isCurrentAccountRemoved);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }

    public void unregisterBroadcastReceiver() {
        broadcastManager.unregisterReceiver(broadcastReceiver);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isConflict && !isCurrentAccountRemoved) {
            updateUnreadLabel();
            //updateUnreadAddressLable();
        }

        DemoHelper sdkHelper = DemoHelper.getInstance();
        sdkHelper.pushActivity(this);
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
    }


    private void loginChatServer() {

        String username = mUser.getData().getUser_id();
        String password = mUser.getData().getChatPass();

        DemoDBManager.getInstance().closeDB();

        DemoHelper.getInstance().setCurrentUserName(username);

        EMClient.getInstance().login(username, password, new EMCallBack() {//回调
            @Override
            public void onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                PreferenceManager.getInstance().setCurrentUserNick(mUser.getData().getCover());
                PreferenceManager.getInstance().setCurrentUserAvatar(mUser.getData().getCover());
                DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();
            }

            @Override
            public void onProgress(int progress, String status) {
                KLog.e(progress + "/" + status);
            }

            @Override
            public void onError(int code, String message) {
                KLog.e("登录聊天服务器失败！" + "/" + code);
            }
        });
    }

    @Override
    protected void onStop() {
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
        DemoHelper sdkHelper = DemoHelper.getInstance();
        sdkHelper.popActivity(this);
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unregisterBroadcastReceiver();
        EMClient.getInstance().contactManager().removeContactListener(myContactListener);
        if (mBuilder != null) {
            mBuilder.create().dismiss();
            mBuilder = null;
            isExceptionDialogShow = false;
        }

    }

    private void showHead() {
        mUser = SPUtil.getUser();
        tv_nickname.setText(mUser.getData().getNickname());
        CommonUtils.loadImageView(this, mUser.getData().getCover(), R.mipmap.default_head, iv_user_head);
        CommonUtils.loadImageView(this, mUser.getData().getCover(), R.mipmap.default_head_image, iv_head_bg);
    }

    private void showVip() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                int userVIP = mUser.getData().getVip_level();
                if (userVIP > 0) {
                    iv_vip.setVisibility(View.VISIBLE);
                } else {
                    iv_vip.setVisibility(View.GONE);
                }
            }
        });

    }

    private void initLeftMenuStatus() {
        showShop();
        showVip();
    }

    private void showShop() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (null == mUser.getData().getShops() || mUser.getData().getShops().size() == 0) {
                    rl_shop_manage.setVisibility(View.GONE);
                } else {
                    rl_shop_manage.setVisibility(View.VISIBLE);
                }
            }
        });


    }


    /**
     * 用户每次打开app，在登录的情况下都要调用 修改用户资料 接口，把district_id改成定位到的地区ID
     */
    private void postLocation() {
        OkHttpUtils.post().url(URL_USER_DATA)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("district_id", SPUtil.getUserLocation().getDistrictId())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                UserEntity userEntity = GsonUtil.fromJson(response, UserEntity.class);
                if (userEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {

                }
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError((Activity) mContext, status_error);
            }
        });
    }

    /**
     * 检查程序更新
     */
    private void checkVersion2Update() {
        if (isNetWorkConnected(this)) {
            StaticDataEntity staticDataEntity = SPUtil.getStaticData();
            if (null != staticDataEntity) {
                try {
                    int localVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
                    int serverVersion = staticDataEntity.getData().getVersion().getAndroid_newest_version();
                    int lowestVersion = staticDataEntity.getData().getVersion().getAndroid_lowest_version();

                    if (localVersion == serverVersion) {
                        SPUtil.putAppFilePath("");
                    }

                    // 如果小于最低支持版本，强制进行更新
                    DefaultDialog.Builder builder_order;
                    if (localVersion < lowestVersion) {
                        builder_order = new DefaultDialog.Builder(MainActivity.this);
                        builder_order.setTitle("版本更新");
                        builder_order.setMessage(getResources().getString(R.string.constraint_update));
                        builder_order.setPositiveButton(R.string.bt_update, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                installNewApp();
                            }
                        });
                        builder_order.create().show();
                    } else {
                        // 如果有新版本，提示更新，但可以忽略更新
                        if (localVersion < serverVersion) {

                            builder_order = new DefaultDialog.Builder(MainActivity.this);
                            builder_order.setTitle("版本更新");
                            builder_order.setMessage(getResources().getString(R.string.hint_update));
                            builder_order.setPositiveButton(R.string.bt_update, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    installNewApp();
                                }
                            });
                            builder_order.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                            builder_order.create().show();
                        }
                    }
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }

            } else {
                ShowToast.showShortToast(getResources().getString(R.string.Network_error));
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataSynEvent(String event) {
        switch (event) {
            case EVENT_USER_HEAD_UPDATE:
                //showHead();
                break;
            case EVENT_UPDATE_USER_STATUS:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        iv_vip.setVisibility(View.VISIBLE);
                    }
                });
                break;
            case EVENT_RESERVATION_SUCCESS:
                refreshUIWithMessage();
                break;
            case EVENT_REFRESH_LEFT:
                initLeftMenuStatus();
                break;
            case EVENT_VIP_CANCEL:
                initLeftMenuStatus();
                break;
            case EVENT_EXIT:
                exitApp();
                break;
            case EVENT_FINISH:
                KLog.e(mUser);
                finish();
                break;
        }
    }

    private void getLocationId(LocationEntity locationEntity) {
        District province = DistrictCache.getInstance(mContext)
                .getCacheByName(locationEntity.getProvinceName(), CODE_PROVINCE);
        District city = DistrictCache.getInstance(mContext)
                .getCacheByName(locationEntity.getCityName(), CODE_CITY);
        District district = DistrictCache.getInstance(mContext)
                .getCacheByName(locationEntity.getDistrictName(), CODE_DISTRICT, city.getId());
        locationEntity.setHomeCityId(city.getId());
        locationEntity.setProvinceId(province.getId());
        locationEntity.setCityId(city.getId());
        locationEntity.setDistrictId(district.getId());
    }

    private void installNewApp() {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse("http://android.myapp.com/myapp/detail.htm?apkName=com.eightbears.beboy");
        intent.setData(content_url);
        startActivity(intent);
    }
}
